#coding:utf-8
import pymysql
import time
import requests
import json
import logging
from logging import handlers

#发货七天后未点击为确认收货地订单通过此脚本运行为确认收货
# 查找出未结算地订单
# 循环执行调用接口将订单表支付表改为已处理并将积分入库
# 记录到日志里面

url_calculation = 'https://teach.idwenshi.com/teach/teach/web/index.php/shell/order'
# url_calculation = 'http://web.teach.com/teach/teach/web/index.php/shell/order'
db = pymysql.Connect(
    host = '127.0.0.1',
    # host = '127.0.0.1',
    port = 3306,
    user = 'root',
    password = 'ekdjpl#45@',
    # password = 'DRsXT5ZJ6Oi55LPQ',
    db = 'teach',
    charset = 'utf8'
)

class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }  # 日志级别关系映射

    def __init__(self, filename, level='info', when='D', backCount=1000,
                 fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)  # 设置日志格式
        self.logger.setLevel(self.level_relations.get(level))  # 设置日志级别
        # sh = logging.StreamHandler()#往屏幕上输出
        # sh.setFormatter(format_str) #设置屏幕上显示的格式
        if not self.logger.handlers:  # 判断对象是否重复实例化,造成同一信息逐一递增输出
            th = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount,
                                                   encoding='utf-8')  # 往文件里写入#指定间隔时间自动生成文件的处理器
            # 实例化TimedRotatingFileHandler
            # interval是时间间隔，backupCount是备份文件的个数，如果超过这个个数，就会自动删除，when是间隔的时间单位，单位有以下几种：
            # S 秒
            # M 分
            # H 小时、
            # D 天、
            # W 每星期（interval==0时代表星期一）
            # midnight 每天凌晨
            th.setFormatter(format_str)  # 设置文件里写入的格式
            # self.logger.addHandler(sh) #把对象加到logger里
            self.logger.addHandler(th)
            # self.logger.removeHandler(sh)
            # self.logger.removeHandler(th)


class DataDeal(object):
    # mall_order stats >=1(已经下单付款的) mall_pay status = 3 已经分佣了并且 时间是发货超过七天的， 拿出这个订单数 发起curl操作
    @staticmethod
    def orders():
        cursor = db.cursor()
        time_now = int(time.time()) # 现在的时间戳
        time_before_seven = time_now - 24 * 60 * 60 * 7 # 七天前的时间戳
        sql = "SELECT p.id AS p_id, p.out_trade_no, p.total_fee, p.status AS p_status, o.id AS o_id, o.mid, o.uid, o.openid,  o.logistic_fee, o.status AS o_status FROM mall_pay AS p LEFT JOIN mall_order AS o ON p.out_trade_no = o.out_trade_no WHERE p.status = 3 AND o.status = 2 AND send_time < %s"
        cursor.execute(sql, (time_before_seven, ))
        return cursor.fetchall()

    @staticmethod
    def change(oid):
        cursor = db.cursor()
        time_now = int(time.time())
        sql_order_change = "UPDATE mall_order SET status = 3, finish_time = %s WHERE id = %s"
        cursor.execute(sql_order_change, (time_now, oid))
        db.commit()



if __name__ == '__main__':
    Logger('/data/wwwroot/default/shell/mall_amount_log/time.log', level='debug').logger.debug("开始执行计划任务")
    DataDeal = DataDeal()
    total_orders = DataDeal.orders()
    if total_orders:
        for total_order in total_orders:
            result = requests.post(url_calculation, data={'oid':total_order[4], 'uid':total_order[6], 'mid':total_order[5],'out_trade_no': total_order[1] })
            res = json.loads(result.text)
            if res['status'] == 200 :
                # 将订单改为已收货 status 跟finish_time
                DataDeal.change(total_order[4])
                Logger('/data/wwwroot/default/shell/mall_amount_log/all.log', level='debug').logger.debug("用户入账成功,用户id:{0},订单号out_trade_no:{1},商家mid:{2}".format(total_order[6], total_order[1], total_order[5]))
            else:
                Logger('/data/wwwroot/default/shell/mall_amount_log/error.log', level='error').logger.error("用户入账失败,用户id:{0},订单号out_trade_no:{1},商家mid:{2}".format(total_order[6], total_order[1], total_order[5]))


    else:
        Logger('/data/wwwroot/default/shell/mall_amount_log/record.log', level='debug').logger.debug("今天没有符合条件的订单处理")

    Logger('/data/wwwroot/default/shell/mall_amount_log/time.log', level='debug').logger.debug("结束计划任务")
